<?php
class FaceBookAPI{
	//const
	public $appid='fill it yourself';
	public $secret='fill it yourself';
	public $permission='publish_stream,read_stream,email,user_photos,user_about_me,user_likes';
	//applink is the link from facebook apps 
	public $appLink='http://apps.facebook.com/helloworldfenixx/?fb_source=bookmark_apps&ref=bookmarks&count=0&fb_bmpos=1_0';
	//http://apps.facebook.com/helloworldfenixx/?fb_source=bookmark_apps&ref=bookmarks&count=0&fb_bmpos=3_0 
	//variable in class
	public $user;
	public $user_id; //fbid, very important
	public $facebook;
	public $user_profile;
	public $access_token;
	public $selfUrl;
	public $logoutUrl;
	public $loginUrl;
	public function init($selfUrl){
		//LV1 init the fb area.
		$this->facebook = new Facebook(array(
		  'appId'  => $this->appid,
		  'secret' => $this->secret,
		  'fileUpload'=> true,
		  'status'=>true,
		  'cookie' => true
		));
		$this->selfUrl=$selfUrl;
		$this->loginUrl=$this->getLoginUrl($this->appid, $this->selfUrl, $this->selfUrl, $this->permission);
		$this->header();
		try{
			$this->user = $this->facebook->getUser();
			$this->user_profile = $this->facebook->api('/me');
			$this->access_token=$this->get_AccessToken();
			$this->user_id=$this->user_profile['id'];
			$this->logoutUrl=$this->facebook->getLogoutUrl();
		}catch(Exception $e){
			//echo "fail".$e;
			$this->user=null;
		}
	}
	public function isLiked(){
		//this function is fail, don't call it!
		$rs1=$this->FBget_likeThisPage();
		print_r($rs1);
		return false;
	}
	public function header(){
		//LV2
		?>
		<meta property="og:title" content="helloworld"/> 
		<meta property="og:type" content="game"/> 
		<meta property="og:image" content="null"/> 
		<meta property="og:url" content="<?php echo $this->selfUrl; ?>"/> 
		<meta property="og:site_name" content="helloworld"/> 
		<meta property="fb:app_id" content="<?php echo $this->appId; ?>"/> 
		<?php
	}
	public function FBget_GraphAPIResponse($url){
		//LV3
		$urls='';
		preg_match('/graph.facebook.com/', $url, $match);
		if(count($match)<=0){
			$urls="https://graph.facebook.com/".$url;
		}else{
			$urls=$url;
		}
		$file=file_get_contents($urls);
		$result=json_decode(urldecode($file), true);
		return $result;
	}
	public function getLoginUrl($apiKey, $cancelUrl, $nextUrl, $permission){
		//LV2
		//$permission: 
		//publish_stream,read_stream,email,user_photos
		//user_about_me,user_likes
		return "https://www.facebook.com/login.php?api_key=$apiKey&cancel_url=$cancelUrl&fbconnect=1&next=$nextUrl&return_session=0&session_version=3&v=1.0&req_perms=$permission";
	}
	
	public function get_AccessToken(){
		if($this->user){
			return $this->facebook->getAccessToken();
		}
	}
	public function getUserProfile(){
		if(!$this->user_profile){
			$this->user_profile=$this->facebook->api('/me');
		}
		return $this->user_profile;
	}
	public function View_login(){
		//LV1 view login page
		if (!$this->user) { //<fb:login-button></fb:login-button>?>
			<a href="<?php echo $this->loginUrl?>" >
			Login
			</a>
		<?php }else{ ?>
			<a href="<?php echo $this->logoutUrl?>" >
				<img id="fb_logout_image" src="http://static.ak.fbcdn.net/images/fbconnect/logout-buttons/logout_small.gif" alt="Connect" />
			</a>
		<?php
		}
	}  
	public function listUserData(){
		if($this->isLogin()){
			return $this->facebook->getLoginUrl();
		}
	}
	public function isLogin(){
		if(!$this->get_AccessToken()){
			return false;
		}
		return true;
	}
	//http://developers.facebook.com/tools/explorer/?method=GET&path=2547256135399
	//https://graph.facebook.com/2547256135399?access_token=AAABnQBRA8V0BAAlyTUSvB03PTdBn3uZA5WJh1O35XW1LejndtJzkwCPHlYZAIEOm01ZAgnRHvRmtZChFn5dKd7dTUfrWGukCLYSxfKIwiNQmIZAgKqgYx
	//https://graph.facebook.com/2547654425356?access_token=AAABnQBRA8V0BACE9gTsAQit1ZCRtkQXge7XAAmyUW6a2ZArEOCbWbdLV23bUbZBTNGpOSPAsTtfkeyQLLcKEW3pkfuI7fIdqxT7YzJlBYZBmhkpWayHK
	public function set_uploadPhoto(){
		$this->facebook->setFileUploadSupport(true);  
		$img = '837150.jpg';
		$photo = $this->facebook->api('/'.$this->user_id.'/photos', 'POST',
                        array( 'source' => '@'.realpath($img),
							   'access_token' => $this->get_AccessToken(), 
                               'message' => 'Yea~~ 終於攪定，用facebook php api上載圖片分享，而且將coding再class化一次，介面更加簡單，今次來一張靈鳥露空~~'
                       ));
		return $photo['id'];
	}
	public function get_uploadPhoto($id){
		try{
			$photo = $this->facebook->api('/'.$this->user.'/photos');
			return $photo;
		}catch(Exception $e){
			echo $e->getMessage();
		}
	}
	public function FBget_likeThisPage(){
		$rs=$this->FBget_GraphAPIResponse(urlencode($this->user_id.'/fql?q=select url from link WHERE url="'.$this->selfUrl.'"&access_token='.$this->access_token));
		return $likes;
	}
	
	public function FBget_allLikes(){
		//LV2
		//get the count of like                                   
		$likes = $this->facebook->api("/me/likes/");
		return $likes;
	}
	public function FBget_countLike(){
		//LV2
		//get the count of like
		$rs=$this->FBget_GraphAPIResponse('fql?q=select total_count from link_stat WHERE url="'.$this->selfUrl.'"');
		return $rs['data']['total_count'];
	}
	public static function fb_like($url){
          echo "<div class=\"fb-like\" data-href=\"" . $url . "\"\n" ;
          echo "data-send=\"true\" data-width=\"642\" data-show-faces=\"true\"></div>\n\n";
	   }
   
       public static function fb_comment($url, $title=''){   
          echo "<div class=\"fb-comments\" data-href=\"" . $url . "\"\n" ;
          echo "data-num-posts=\"5\" data-width=\"642\"><fb:title>".$title."</fb:title></div>\n\n";
       }
	public function footer(){
		//LV1 the must code for fb interface
		?>
		<div id="fb-root"></div>
		<script>
			window.fbAsyncInit = function() {
				FB.init({
				  appId: '<?php echo $this->facebook->getAppID() ?>',
				  status: true,
				  cookie: true,
				  
				  xfbml: true,
				  oauth: true
				});
				FB.Event.subscribe('auth.login', function(response) {
				  window.location.reload();
				});
				FB.Event.subscribe('auth.logout', function(response) {
				  window.location.reload();
				});
			};
		  (function() {
			var e = document.createElement('script'); e.async = true;
			e.src = document.location.protocol +
			  '//connect.facebook.net/en_US/all.js';
			document.getElementById('fb-root').appendChild(e);
		  }());
</script>

    </script>
		<?php
	}
}
?>